package com.Android.Intr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BlogActivity extends ListActivity {
	static ArrayList<BlogEntry> blogs;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  final SharedPreferences settings = getSharedPreferences("PREF", 0);
	  String username = settings.getString("Username", "");
	  String[] listOfBlogs = null;
	  try {
		  listOfBlogs = requestBlogsFromServer(username);
	  } catch (JSONException e) {
	  } catch (Exception e) {
	  }
	  int a = 5;
	  setListAdapter(new ArrayAdapter<String>(this, R.layout.blogitem, listOfBlogs));
	  
	  ListView lv = getListView();
	  lv.setTextFilterEnabled(true);
	  /*
	  lv.setOnItemClickListener(new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	      // When clicked, show a toast with the TextView text
	      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
	          Toast.LENGTH_SHORT).show();
	    }
	  });
	  */
	  
	  lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		    	Intent toBlog = new Intent(BlogActivity.this, BlogViewActivity.class);
		    	toBlog.putExtra("author", blogs.get(position).getAuthor());
		    	toBlog.putExtra("content", blogs.get(position).getContent());
		    	toBlog.putExtra("added", blogs.get(position).getDate());
		    	toBlog.putExtra("model", blogs.get(position).getModel());
		    	toBlog.putExtra("pk", blogs.get(position).getPk());
		    	toBlog.putExtra("society", blogs.get(position).getSociety());
		    	toBlog.putExtra("title", blogs.get(position).getTitle());
				startActivity(toBlog);
		    }
		  });
	}
	
	//Menu stuff
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.refresh_menu:
	    	Toast toast = Toast.makeText(getApplicationContext(), "Refresh taking place", Toast.LENGTH_SHORT);
	        toast.show();
	        return true;
	    case R.id.logout_menu:
	    	Toast toast2 = Toast.makeText(getApplicationContext(), "Logging out", Toast.LENGTH_SHORT);
	        toast2.show();
	        //remove authentication data
	        SharedPreferences.Editor editor = getSharedPreferences("PREF", 0).edit();
			editor.putBoolean("Authenticated", false);
			editor.putString("Username", "");
			editor.putString("Password", "");
			editor.commit();
			
			Intent toHome = new Intent(BlogActivity.this, IntrActivity.class);
			startActivity(toHome);
	        return true;  
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	String[] requestBlogsFromServer(String username) throws JSONException{
		String urlString = "http://intr.ep.io/blogs/user.json?username=dan";
		//String urlString = "http://intr.ep.io/blogs/user.json?username="+username;
		String str = null;
		JSONArray result = null;
	    //JSONObject result = null;
		
		URL url;
		try {
			url = new URL(urlString);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
			str = in.readLine();
			in.close();
			
			
		} catch (MalformedURLException e) {
		} catch (IOException e) {
			Toast connectionFailed = Toast.makeText(getApplicationContext(), "Connection failed!", Toast.LENGTH_SHORT);
			connectionFailed.show();
		}
	   	
		result = new JSONArray(str);//result - the whole JSONArray
		String[] s = new String[result.length()];
		blogs = new ArrayList<BlogEntry>();
		
		for(int i=0;i<result.length();i++){
			BlogEntry temp = new BlogEntry();
			temp.setAuthor( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("author") );
			temp.setContent( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("content") );
			temp.setDate( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("added") );
			temp.setModel(((JSONObject)result.get(i)).getString("model"));
			temp.setPk(((JSONObject)result.get(i)).getInt("pk"));
			temp.setSociety( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("society") );
			temp.setTitle( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("title") );
			blogs.add(temp);			
		}
		//Collections.sort(blogs);
		for(int i=0;i<blogs.size();i++){
			s[i] = blogs.get(i).getDateTitleAuthor();
		}
		return s;
	}
}
